<template>
  <u-index-list :index-list="stationList.indexList">
    <template v-for="(item, index) in stationList.itemArr">
      <u-index-item>
        <u-index-anchor :text="stationList.indexList[index]"></u-index-anchor>
        <view
          v-for="(cell, i) in item"
          @tap="handleSelectedStation(cell)"
          class="py-base mx-base"
          :class="[{ 'u-border-bottom': i !== item.length - 1 }]"
          >{{ cell }}</view
        >
      </u-index-item>
    </template>
  </u-index-list>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      key: "",
    };
  },
  computed: {
    ...mapState({ stations: "stations" }),
    stationList() {
      // updateStations 中已对 stations 进行排序
      const indexList = [];
      const itemArr = [];
      for (const station of this.stations) {
        const currChar = indexList.slice(-1)[0];
        const char = station.pinyin[0];
        if (currChar === char) {
          itemArr.slice(-1)[0].push(station.name);
        } else {
          indexList.push(char);
          itemArr.push([station.name]);
        }
      }
      return { indexList, itemArr };
    },
  },
  onLoad(query) {
    const { key } = query;
    this.key = key;
  },
  methods: {
    handleSelectedStation(stationName) {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.$vm[this.key] = stationName;
      uni.navigateBack({ delta: 1 });
    },
  },
};
</script>
